<?php
namespace app\index\controller;
use think\Controller;
use GatewayClient\Gateway;

class Index extends Controller
{
    protected $tpl='';
    
    public function __construct(\think\App $app = null) {
        parent::__construct($app);
        if(!session('?user_id')){
            $this->error('非法操作!');
        }
    }

     public function index(){
         if(request()->isMobile()){
             $this->tpl = 'mobile@index/index';
         }
         
        $fromid = (int)input('fromid');
        $toid = (int)input('toid');
//        halt($fromid);
        if($fromid != session('user_id') || $fromid == $toid){
            $this->error("非法操作!");
        }
        
        if(!isset($fromid) || !isset($toid)){
            $this->error('系统异常,请重新登陆', url('index/login/index'));
        }
        
        $users = db('users')->where('id','neq',$fromid)->select();        //halt($users);
        
        foreach ($users as $key => $value) {
            $lastMsgInfo = db('msg')->field('content,time,type')->where('fromid = ? AND toid = ?',[$value['id'],$fromid])->order('time desc')->find();
            $users[$key]['lastMsg'] = $lastMsgInfo['type'] == 0 ? $lastMsgInfo['content'] : '[图片]';
            $users[$key]['time'] = empty($lastMsgInfo['time']) ? '' : date('Y-m-d H:i:s',$lastMsgInfo['time']);
            
            $noRead = db('msg')->where('fromid = ? AND toid = ? AND is_read = 0',[$value['id'],$fromid])->count();           // halt($noRead);
            $users[$key]['noRead'] = $noRead > 0 ? $noRead : '';
            $users[$key]['nick_name'] = strlen($value['nick_name']) > 15 ? substr($value['nick_name'],0,15).'...' : $value['nick_name'];
        }
//        halt($users);
        $this->assign('users',$users);
        $this->assign('fromid',$fromid);
        $this->assign('toid',$toid);
        return $this->fetch($this->tpl);
    }
    
}
